package com.onenine.app.danmu;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.drawable.Drawable;
import android.support.v4.app.ActivityCompat;
import android.text.TextPaint;

import com.onenine.app.R;
import com.onenine.app.model.BarrageItem;
import com.onenine.app.utils.DataType;
import com.onenine.app.utils.RoleResLoader;
import com.onenine.common.util.Logger;

import master.flame.danmaku.danmaku.model.BaseDanMu;
import master.flame.danmaku.danmaku.model.android.AndroidDisplayer;
import master.flame.danmaku.danmaku.model.android.BaseCacheStuffer;

/**
 * 弹幕绘制
 */
public class DanmuCacheStuffer extends BaseCacheStuffer {

    private Context mContext;
    private int mStrokeWidth;
    private int mImgSize; //头像或图标直径
    private int mContentPadding; // 内边距
    private int mContentTextSize; // 内容文字大小
    private int mMediaIconSize; //音频或图片图标大小
    private Paint mMainPaint = new Paint();
    private Paint mBgPaint = new Paint();
    private Paint mTextPaint = new Paint();
    private BarrageItem mBarrageItem;
    private Drawable mImgBitmap, mVoiceBitmap, mImgClickBitmap, mVoiceClickBitmap;
    private int mRoundRadius;
    private int mDefaultBgColor;
    private int[] mFemaleBgColor, mMaleBgColor;

    public DanmuCacheStuffer(Context context) {
        mContext = context;
        mStrokeWidth = dp2px(mContext, 2);
        mContentPadding = dp2px(mContext, 4);
        mRoundRadius = dp2px(mContext, 30);
        mDefaultBgColor = ActivityCompat.getColor(context, R.color.barrage_item_bg);
        mFemaleBgColor = new int[]{0XFFFE64CE, 0XFFFD8BAC, 0XFFFB9D9E};
        mMaleBgColor = new int[]{0XFF36BDFD, 0XFF5FD7FB, 0XFF6BE3FA};
        mImgBitmap = ActivityCompat.getDrawable(context, R.drawable.ic_barrage_item_img);
        mVoiceBitmap = ActivityCompat.getDrawable(context, R.drawable.ic_barrage_item_voice);
        mImgClickBitmap = ActivityCompat.getDrawable(context, R.drawable.ic_barrage_item_img_click);
        mVoiceClickBitmap = ActivityCompat.getDrawable(context, R.drawable.ic_barrage_item_voice_click);
        //设置颜色和搞锯齿
        mMainPaint.setColor(Color.RED);
        mMainPaint.setAntiAlias(true);
        mMainPaint.setFilterBitmap(true);
        mTextPaint.setAntiAlias(true);
        mTextPaint.setColor(Color.WHITE);
        mBgPaint.setStyle(Paint.Style.FILL);
    }

    @Override
    public void measure(BaseDanMu danmaku, TextPaint paint, boolean fromWorkerThread) {
        //初始化数据
        mBarrageItem = (BarrageItem) danmaku.tag;
        //设置弹幕项的随机尺寸
        setRandomDanmuSize();
        //设置文本画笔
        mTextPaint.setTextSize(mContentTextSize);

        if (mBarrageItem.getContent().length() > 10) {
            mBarrageItem.setContent(mBarrageItem.getContent().substring(0, 10) + "...");
        }

        // 计算名字和内容的长度，取最大值
        float contentWidth = mTextPaint.measureText(mBarrageItem.getContent());

        // 设置弹幕区域的宽高
        danmaku.paintHeight = mImgSize + mContentPadding * 2; // 设置弹幕区域的高度
        if (mBarrageItem.getBarrageType() == DataType.BARRAGE_TEXT) {
            //文本
            danmaku.paintWidth = contentWidth + mImgSize + 2 * (danmaku.padding + mContentPadding + mContentPadding); // 设置弹幕区域的宽度
        } else {
            //图片或音频
            danmaku.paintWidth = contentWidth + mMediaIconSize + mImgSize + 2 * (mContentPadding + mContentPadding + danmaku.padding); // 设置弹幕区域的宽度
        }
    }

    /**
     * 设置弹幕项的尺寸
     * 随机大小,4种风格
     */
    private void setRandomDanmuSize() {
        int ret = mBarrageItem.getIdentificationCode() % 4;
        int alpha;
        switch (ret) {
            case 0:
                mImgSize = dp2px(mContext, 48);
                mMediaIconSize = dp2px(mContext, 24);
                mContentTextSize = dp2px(mContext, 20);
                alpha = 0xff;
                break;
            case 1:
                mImgSize = dp2px(mContext, 40);
                mMediaIconSize = dp2px(mContext, 20);
                mContentTextSize = dp2px(mContext, 18);
                alpha = 0xd3;
                break;
            case 2:
                mImgSize = dp2px(mContext, 32);
                mMediaIconSize = dp2px(mContext, 16);
                mContentTextSize = dp2px(mContext, 14);
                alpha = 0xb7;
                break;
            default:
                mImgSize = dp2px(mContext, 24);
                mMediaIconSize = dp2px(mContext, 12);
                mContentTextSize = dp2px(mContext, 10);
                alpha = 0x80;
                break;
        }

        if (mBarrageItem.isTouchClick()) {
            mMainPaint.setAlpha(0xff);
            mTextPaint.setAlpha(0xff);
        } else {
            mMainPaint.setAlpha(alpha);
            mTextPaint.setAlpha(alpha);
        }
    }

    /**
     * 绘制背景
     *
     * @param danmaku
     * @param canvas
     * @param left
     * @param top
     */
    private void drawBackground(BaseDanMu danmaku, Canvas canvas, float left, float top) {
        RectF arcRect = new RectF(left + mImgSize + 2 * mContentPadding,
                top + mContentPadding, danmaku.paintWidth, (top + mContentPadding + mImgSize + mStrokeWidth));
        if (mBarrageItem.isTouchClick()) {
            mBgPaint.setAlpha(mMainPaint.getAlpha());
            if (mBarrageItem.getSex() == DataType.SEX_FEMALE) {
                mBgPaint.setShader(new LinearGradient(arcRect.left, arcRect.top, arcRect.right, arcRect.bottom
                        , mFemaleBgColor, null, Shader.TileMode.CLAMP));
            } else {
                mBgPaint.setShader(new LinearGradient(arcRect.left, arcRect.top, arcRect.right, arcRect.bottom
                        , mMaleBgColor, null, Shader.TileMode.CLAMP));
            }
        } else {
            mBgPaint.setShader(null);
            mBgPaint.setColor(mDefaultBgColor);
            mBgPaint.setAlpha((int) (mMainPaint.getAlpha() * 0.2));
        }
        canvas.drawRoundRect(arcRect, mRoundRadius, mRoundRadius, mBgPaint);
    }

    @Override
    public void drawDanmaku(BaseDanMu danmaku, Canvas canvas, float left, float top
            , boolean fromWorkerThread, AndroidDisplayer.DisplayerConfig displayerConfig) {

        //初始化
        left += danmaku.padding;
        top += danmaku.padding;
        if (danmaku.borderColor != 0) {
            left += AndroidDisplayer.DisplayerConfig.BORDER_WIDTH;
            top += AndroidDisplayer.DisplayerConfig.BORDER_WIDTH;
        }

        //绘制背景
        drawBackground(danmaku, canvas, left, top);

        // 绘制头像
        int avatarLeft = (int) (left + mContentPadding);
        int avatarTop = (int) (top + mContentPadding);
        int avatarRight = (int) (left + mContentPadding + mImgSize);
        int avatarBottom = (int) (top + mContentPadding + mImgSize);
        Drawable avatarDrawable = mBarrageItem.getAvatarDrawable();
        if (avatarDrawable != null) {
            avatarDrawable.setAlpha(mMainPaint.getAlpha());
            avatarDrawable.setBounds(new Rect(avatarLeft, avatarTop, avatarRight, avatarBottom));
            avatarDrawable.draw(canvas);
        }
        //绘制外边
        mMainPaint.setStrokeWidth(mStrokeWidth);
        mMainPaint.setStyle(Paint.Style.STROKE);
        int srcAlpha = mMainPaint.getAlpha();
        if (mBarrageItem.isTouchClick()) {
            mMainPaint.setColor(RoleResLoader
                    .getRoleColorResourceId(RoleResLoader.DynamicResName.THEME_COLOR, mBarrageItem.getSex()));
        } else {
            mMainPaint.setColor(Color.WHITE);
        }
        mMainPaint.setAlpha(srcAlpha);
        canvas.drawArc(new RectF(avatarLeft, avatarTop, avatarRight, avatarBottom)
                , 0f, 360f, false, mMainPaint);

        // 绘制内容
        float contentLeft = left + mImgSize + mContentPadding * 6;
        float contentRight = contentLeft + mTextPaint.measureText(mBarrageItem.getContent());
        float contentBottom = avatarTop + (mImgSize + mStrokeWidth) / 2 + Math.abs(mTextPaint.ascent() + mTextPaint.descent()) / 2;
        canvas.drawText(mBarrageItem.getContent(), contentLeft, contentBottom, mTextPaint);

        //绘制音图图标
        int mediaLeft = (int) contentRight + mContentPadding;
        int mediaTop = (int) ((danmaku.paintHeight - mMediaIconSize) / 2);
        int mediaRight = mediaLeft + mMediaIconSize;
        int mediaBottom = mediaTop + mMediaIconSize;
        if (mBarrageItem.getBarrageType() == DataType.BARRAGE_IMAGE
                || mBarrageItem.getBarrageType() == DataType.BARRAGE_IMAGE_TEXT) {
            if (mBarrageItem.isTouchClick()) {
                mImgClickBitmap.setBounds(new Rect(mediaLeft, mediaTop, mediaRight, mediaBottom));
                mImgClickBitmap.draw(canvas);
            } else {
                mImgBitmap.setAlpha(mMainPaint.getAlpha());
                mImgBitmap.setBounds(new Rect(mediaLeft, mediaTop, mediaRight, mediaBottom));
                mImgBitmap.draw(canvas);
            }
        } else if (mBarrageItem.getBarrageType() == DataType.BARRAGE_VOICE
                || mBarrageItem.getBarrageType() == DataType.BARRAGE_VOICE_TEXT) {
            if (mBarrageItem.isTouchClick()) {
                mVoiceClickBitmap.setBounds(new Rect(mediaLeft, mediaTop, mediaRight, mediaBottom));
                mVoiceClickBitmap.draw(canvas);
            } else {
                mVoiceBitmap.setAlpha(mMainPaint.getAlpha());
                mVoiceBitmap.setBounds(new Rect(mediaLeft, mediaTop, mediaRight, mediaBottom));
                mVoiceBitmap.draw(canvas);
            }
        }
        mBarrageItem.setTouchClick(false);
    }

    @Override
    public void clearCaches() {
        Logger.e("弹幕clearCaches");
        mBarrageItem = null;
        mImgBitmap = null;
        mVoiceBitmap = null;
        mVoiceClickBitmap = null;
        mImgClickBitmap = null;
    }

    private int dp2px(Context context, final float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

}
